<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog system-user-dialog"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      :title="dataList.InspectionPlanInfo"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      @closed="closeDialog"
    >
      <el-form
        ref="formData"
        class="base-pipeline-layout system-user-form"
        label-width="120px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-form-item
          :label="dataList.InspectionPlan"
          prop="verificationId"
          :error="errorMsg.verificationId"
        >
          <el-select
            v-model="formData.verificationId"
            :placeholder="dataList.Placeholder"
            @change="deviceVerificationChange"
          >
            <el-option
              v-for="item in deviceVerificationList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :label="dataList.PlanName"
          :error="errorMsg.name"
          prop="name"
        >
          <el-input v-model="formData.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          :label="dataList.DeadlineDate"
          :error="errorMsg.endDate"
          prop="endDate"
        >
          <el-date-picker
            v-model="formData.endDate"
            type="date"
            :placeholder="dataList.SelectDateTime"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <br />
        <div class="base-content-operate" style="float: left">
          <el-input
            v-model="deviceNameNum"
            :placeholder="dataList.EnterContent"
            class="input-with-select"
            style="width: 200px; margin-left: 10px"
          >
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
          <el-button
            type="primary"
            style="margin-left: 5px"
            @click="batchSetting"
            >{{ btn.BatchSetting }}</el-button
          >
        </div>
        <br />
        <div style="width: 100%">
          <el-table
            ref="deviceVerificationPlan"
            :key="bomCheckKey"
            :data="listData"
            element-loading-text="Loading"
            height="430"
            fit
            highlight-current-row
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column :label="dataList.DeviceNumber">
              <template slot-scope="scope">
                {{ scope.row.deviceDto.num }}
              </template>
            </el-table-column>
            <el-table-column
              :label="
                $i18n.locale === 'en'
                  ? dataList.DeviceEName
                  : dataList.DeviceName
              "
            >
              <template slot-scope="scope">
                {{ scope.row.deviceDto.name }}
              </template>
            </el-table-column>
            <el-table-column :label="dataList.DeviceSpecifications">
              <template slot-scope="scope">
                {{ scope.row.deviceDto.specifications }}
              </template>
            </el-table-column>
            <el-table-column :label="dataList.DevicePersonResponsibleId">
              <template slot-scope="scope">
                {{ scope.row.deviceDto.personResponsibleName }}
              </template>
            </el-table-column>

            <el-table-column :label="dataList.ScheduledInspectionTime">
              <template slot-scope="scope">
                {{
                  Number(scope.row.isVerification) === 0
                    ? "/"
                    : formatTime(scope.row.verificationPlanDate)
                }}
              </template>
            </el-table-column>
            <el-table-column :label="dataList.Week">
              <template slot-scope="scope">
                {{
                  Number(scope.row.isVerification) === 0
                    ? "/"
                    : scope.row.cycle + scope.row.cycleName
                }}
              </template>
            </el-table-column>
            <el-table-column :label="dataList.Inspector">
              <template slot-scope="scope">
                {{
                  Number(scope.row.isVerification) === 0
                    ? "/"
                    : scope.row.verificationPersonName
                }}
              </template>
            </el-table-column>
            <el-table-column :label="dataList.CheckOrNot">
              <template slot-scope="scope">
                {{ scope.row.isVerificationName }}
                <span
                  v-if="Number(scope.row.isVerification) === 0"
                  style="color: red"
                  >{{ dataList.Deny }}</span
                >
                <span v-else-if="Number(scope.row.isVerification) === 1">{{
                  dataList.Correct
                }}</span>
                <span v-else></span>
              </template>
            </el-table-column>
            <el-table-column :label="dataList.Operation">
              <template slot-scope="scope">
                <div class="base-table-operation">
                  <el-link
                    style="margin-left: 5px"
                    size="mini"
                    type="primary"
                    @click="setting(scope.row)"
                    >{{ btn.Setting }}</el-link
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit('formData')">{{
          btn.Save
        }}</el-button>
        <el-button
          type="primary"
          style="width: 120px"
          @click="onSaveSubmit('formData')"
          >{{ btn.SaveAndSubmit }}</el-button
        >
        <el-button @click="cancel">{{ btn.Cancel }}</el-button>
      </div>
    </el-dialog>
    <DeviceVerificationPlanSettingDialog
      v-if="settingVisible"
      ref="DeviceVerificationPlanSettingDialog"
      :dialog-form-setting-visible.sync="settingVisible"
      :verification-person.sync="verificationPerson"
      :device-verification-plan-info-dto.sync="deviceVerificationPlanInfoDto"
      @settingDialogClose="settingDialogClose"
    />
  </div>
</template>

<script>
import {
  update,
  getList as deviceVerificationPlanList,
  updateAndVerifyStart,
} from "../../../api/DeviceVerificationPlan.js";
import { getList } from "../../../api/DeviceVerification";
import DeviceVerificationPlanSettingDialog from "./DeviceVerificationPlanSettingDialog.vue";
import { formatTime } from "../../../utils/time";
export default {
  name: "DeviceVerificationPlanEditDialog",
  components: { DeviceVerificationPlanSettingDialog },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: String,
      default: "0",
    },
  },
  data() {
    return {
      deviceVerificationPlanInfoDtoList: [],
      bomCheckKey: 0,
      rows: [],
      deviceVerification: {},
      deviceVerificationList: [],
      deviceNameNum: "",
      list: [],
      deviceVerificationPlanInfoDto: {},
      verificationPerson: "",
      settingVisible: false,
      idList: [],
      tableDatas: [],
      options: [],
      loading: false,
      innerDialogFormVisible: false,
      formLabelWidth: "100px",
      initData: {
        id: 0,
        num: "",
        name: "",
        endDate: null,
        verificationId: "",
        status: 0,
        statusName: "",
        creator: 0,
        creatorName: "",
        assertDate: "",
        remark: "",
      },
      formData: {
        id: 0,
        num: "",
        name: "",
        endDate: null,
        verificationId: "",
        status: 0,
        statusName: "",
        creator: 0,
        creatorName: "",
        assertDate: "",
        remark: "",
        deviceVerificationPlanInfoCreateRequest: [],
      },
      // 限制日期
      pickerOptions: {
        // 限制日期
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      formDataRules: {
        name: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        endDate: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        verificationId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      initErrorMsg: {
        num: "",
        name: "",
        endDate: "",
        verificationId: "",
        status: "",
        statusName: "",
        creator: "",
        creatorName: "",
        assertDate: "",
        remark: "",
      },
      errorMsg: {
        num: "",
        name: "",
        endDate: "",
        verificationId: "",
        status: "",
        statusName: "",
        creator: "",
        creatorName: "",
        assertDate: "",
        remark: "",
      },
    };
  },
  computed: {
    listData() {
      if (this.deviceVerificationPlanInfoDtoList === undefined) {
        return null;
      } else {
        return this.deviceVerificationPlanInfoDtoList.filter((record) => {
          return (
            record.deviceDto.num.includes(this.deviceNameNum) ||
            record.deviceDto.name.includes(this.deviceNameNum)
          );
        });
      }
    },
    btn() {
      return this.$t("ModuleDevice.buttons");
    },
    dataList() {
      return this.$t("ModuleDevice.Device");
    },
  },
  watch: {},
  created() {
    this.initdata();
  },
  methods: {
    formatTime,
    isVerification() {
      var flag = true;
      var flag2 = false;
      this.deviceVerificationPlanInfoDtoList.map((item) => {
        if (item.isVerification === "") {
          flag = false;
        }
        if (item.isVerification === 1 || item.isVerification === "1") {
          flag2 = true;
        }
      });
      return flag && flag2;
    },
    initdata() {
      getList({ status: 30 }, { pageIndex: 1, pageSize: 1000000 })
        .then((res) => {
          this.deviceVerificationList = res.data.dataList;
        })
        .catch((res) => {});
      deviceVerificationPlanList({ id: this.editId }).then((res) => {
        if (res.data.dataList.length > 0) {
          this.formData = res.data.dataList[0];
          this.deviceVerificationPlanInfoDtoList =
            this.formData.deviceVerificationPlanInfoDtoList;
          this.verificationId = this.formData.verificationId;
        }
      });
    },
    deviceVerificationChange(v) {
      if (this.verificationId === v) {
        this.deviceVerificationPlanInfoDtoList =
          this.formData.deviceVerificationPlanInfoDtoList;
      } else {
        this.deviceVerificationList.map((item) => {
          if (item.id === v) {
            this.deviceVerification = item;
            this.deviceVerification.deviceVerificationInfoDtoList.map(
              (item2) => {
                item2.verificationPlanDate = "";
                item2.cycle = "";
                item2.cycleName = "";
                item2.verificationPersonName = "";
                item2.isVerification = "";
                item2.VerificationPerson = item2.deviceDto.personResponsibleId;
              }
            );

            this.deviceVerificationPlanInfoDtoList =
              this.deviceVerification.deviceVerificationInfoDtoList;
          }
        });
      }
    },
    // 单个设置
    setting(row) {
      this.rows = [];
      this.rows.push(row);
      this.deviceVerificationPlanInfoDto = row;
      this.settingVisible = true;
    },
    settingDialogClose(data) {
      if (data.isVerification === "" || data.cycle === "") {
        data.verificationPerson = 0;
        data.verificationPersonName = "";
      }
      this.rows.map((item) => {
        var strJson = JSON.parse(JSON.stringify(data));
        item.cycle = strJson.cycle;
        item.cycleName = strJson.cycleName;
        item.isVerification = strJson.isVerification;
        item.isVerificationName = strJson.isVerificationName;
        item.unit = strJson.unit;
        item.verificationPerson = strJson.verificationPerson;
        item.verificationPersonName = strJson.verificationPersonName;
        item.verificationPlanDate = strJson.verificationPlanDate;
      });
      this.deviceVerificationPlanInfoDto = {};
      this.$nextTick(() => {
        this.bomCheckKey++;
      });
    },
    handleSelectionChange(val) {
      this.tableDatas = val;
      this.idList = this.tableDatas.map((item) => item.id);
    },
    // 批量设置
    batchSetting() {
      var rows = this.$refs.deviceVerificationPlan.selection;
      if (rows === null || rows.length === 0) {
        this.$message.warning(this.$t("ModuleDevice.Message.SelectDevice"));
        return false;
      }
      this.rows = rows;
      this.settingVisible = true;
    },
    cancel() {
      this.$emit("update:dialogFormVisible", false);
    },
    closeDialog() {
      this.$parent.getList();
      this.cancel();
    },
    onSubmit() {
      var flag = this.isVerification();
      if (!flag) {
        this.$message.warning(
          this.$t("ModuleDevice.Message.EquipCheckMessage2")
        );
        return;
      }
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          var list = [];
          this.deviceVerificationPlanInfoDtoList.map((item) => {
            var obj = item;
            obj.deviceId = item.deviceDto.id;
            list.push(obj);
          });
          this.formData.status = "10";
          this.formData.statusName = this.dataList.PeddingSubmission;
          this.formData.deviceVerificationPlanInfoDtoList = list;

          update(this.formData)
            .then((res) => {
              if (res.code === 200) {
                this.closeDialog();
              } else {
                this.showValidateMsgCheck(res);
              }
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    onSaveSubmit() {
      var flag = this.isVerification();
      if (!flag) {
        this.$message.warning(
          this.$t("ModuleDevice.Message.EquipCheckMessage2")
        );
        return;
      }
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          var list = [];
          this.deviceVerificationPlanInfoDtoList.map((item) => {
            var obj = item;

            obj.deviceId = item.deviceDto.id;
            list.push(obj);
          });
          this.formData.status = "20";
          this.formData.statusName = this.dataList.UnderReview;
          this.formData.deviceVerificationPlanInfoDtoList = list;
          updateAndVerifyStart(this.formData)
            .then((res) => {
              if (res.code === 200) {
                this.closeDialog();
              } else {
                this.showValidateMsgCheck(res);
              }
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("num", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("name", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("endDate", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("verificationId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("status", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("statusName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("creator", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("creatorName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("assertDate", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("remark", this.errorMsg, res.msg);
      }
    },
  },
};
</script>
